package com.pvdnc.riru.appinjector;

import android.os.IBinder;
import android.util.Log;

import com.pvdnc.riru.common.ServiceObserver;

import java.lang.reflect.Method;

import andhook.lib.xposed.XC_MethodHook;
import andhook.lib.xposed.XposedBridge;

public class HookPMS extends ServiceObserver {
    private static final String TAG=HookPMS.class.getSimpleName();

    public static final HookPMS INSTANCE=new HookPMS();

    @Override
    public void onServiceAdd(String name, IBinder service) {
        try{
            LoadablePackages.initPrivileged();
            hookGetDefaultBrowserPackageName(service);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void hookGetDefaultBrowserPackageName(IBinder pms) throws Exception{
        Method method=pms.getClass().getDeclaredMethod("getDefaultBrowserPackageName",int.class);
        XposedBridge.hookMethod(method,new XC_MethodHook(){
            @Override
            protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                super.beforeHookedMethod(param);
                int opCode= (int) param.args[0];
                if(Integer.MAX_VALUE!=opCode)
                    return;
                String json= LoadablePackages.fromFile().toJson();
                Log.d(TAG,"return hookable pkgs json:\n\t"+json);
                param.setResult(json);
            }
        });
        Log.d(TAG,"finish hooking getDefaultBrowserPackageName");
    }
}
